package com.hb0730.boot.admin.modules.sci.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hb0730.boot.admin.base.R;
import com.hb0730.boot.admin.base.util.NamingUtil;
import com.hb0730.boot.admin.core.service.BaseServiceImpl;
import com.hb0730.boot.admin.modules.sci.mapper.SciMessageMapper;
import com.hb0730.boot.admin.modules.sci.model.entity.SciMessage;
import com.hb0730.boot.admin.modules.sci.util.TypeTableUtil;
import com.hb0730.boot.admin.security.model.Authority;
import com.hb0730.boot.admin.security.model.UserInfo;
import com.hb0730.boot.admin.security.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class SciMessageService extends BaseServiceImpl<SciMessageMapper, SciMessage> {
    @Transactional(rollbackFor = Exception.class)
    public R<SciMessage> saveMessage(SciMessage sciMessage) {
//        String newPath = sciMessage.getType();
        UserInfo userInfo = SecurityUtil.getCurrentUser();
        sciMessage.setUsername(userInfo.getUsername());
        sciMessage.setCreatedBy(userInfo.getNickname());
        sciMessage.setModifiedBy(userInfo.getNickname());
        sciMessage.setDepartment(userInfo.getDepartment());
        sciMessage.setType(sciMessage.getType());
        sciMessage.setProposal(null);
        sciMessage.setStatus(3);
        return save(sciMessage) ? R.OK(sciMessage) : R.NG("添加失败");
    }
    public R<SciMessage> updateMessage(Integer status, SciMessage sciMessage) {
        try {
            if (checkRoleOrPermission(status)) {
                UserInfo userInfo = SecurityUtil.getCurrentUser();
                if (sciMessage.getId() == null || sciMessage.getId().isEmpty()) {
                    String id = findIdBySciId(sciMessage.getSciId());
                    sciMessage.setId(id);
                }
                sciMessage.setStatus(status);
                // 设置修改者信息
                sciMessage.setModifiedBy(userInfo.getNickname());
                String tableName = TypeTableUtil.getTableName(sciMessage.getType());
                updateById(sciMessage);
                this.baseMapper.updateProStatus(tableName, sciMessage);
                return R.OK("更新成功");
            } else {
                return R.NG("没有权限更新");
            }
        } catch (Exception e) {
            log.error("更新消息时发生错误: {}", e.getMessage(), e);
            return R.NG("更新失败: " + e.getMessage());
        }
    }

    private String findIdBySciId(String sciId) {
        return this.baseMapper.findIdBySciId(sciId);
    }

    private boolean checkRoleOrPermission(Integer status) {
        Collection<Authority> currentPermissions = SecurityUtil.getCurrentPermission();
        List<String> permission = currentPermissions.stream().map(Authority::getAuthority).toList();
        // 如果用户是管理员，直接更新
        if (permission.contains("admin") ||
                (permission.contains("dep_head") && (Objects.equals(status, 1) || Objects.equals(status, 4))) ||
                (permission.contains("sch_head") && (Objects.equals(status, 2) || Objects.equals(status, 5))) ||
                (permission.contains("user") && (Objects.equals(status, 0) || Objects.equals(status, 3)))) {
            return true;
        }
        return false;
    }

    public List<SciMessage> msgList() {
        UserInfo userInfo = SecurityUtil.getCurrentUser();
        List<String> roles = userInfo.getRoles();
        List<String> permissions = userInfo.getPermissions();
        LambdaQueryWrapper<SciMessage> queryWrapper = Wrappers.lambdaQuery(SciMessage.class);
        if (!roles.contains("admin")) {
            if (permissions.contains("sci:paper:conference:query:dep_head")) {
                queryWrapper.eq(SciMessage::getDepartment,userInfo.getDepartment());
                queryWrapper.eq(SciMessage::getStatus,3);
            } else if (permissions.contains("sci:paper:conference:query:user")) {
                queryWrapper.eq(SciMessage::getUsername,userInfo.getUsername());
            } else if (permissions.contains("sci:paper:conference:query:sch_head")) {
                queryWrapper.eq(SciMessage::getStatus,4);
            }else if(permissions.contains("sci:paper:conference:query:reviewer")){
                return new ArrayList<>();
            }
        }
        return this.list(queryWrapper);
    }

    public R<String> deleteByIds(List<String> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return R.NG("参数不能为空");
        }
        removeByIds(ids);
        return R.OK();
    }

    public Map<String, Object> msgRecent() {
        List<SciMessage> res = this.msgList();
        if(res.isEmpty()) return new HashMap<>();
        List<Map<String, Object>> sciListAll = new ArrayList<>();
        Map<String, List<String>> groupedSciIds = groupByType(res);
        groupedSciIds.forEach((type, sciIds) -> {
            String tableName  = TypeTableUtil.getTableName(type);
            List<Map<String, Object>> sciList = this.baseMapper.getSciList(tableName,sciIds);
            sciListAll.addAll(sciList);
        });// 根据 type 分类 sciId
        List<Map<String, Object>> sciListAllName = NamingUtil.convertToCamelCase(sciListAll);
        System.out.println(sciListAllName);
        Map<String, Object> result = new HashMap<>();

        // audit 和 reject 分类对象
        Map<String, List<Map<String, Object>>> audit = new HashMap<>();
        Map<String, List<Map<String, Object>>> reject = new HashMap<>();

        // 遍历 sciListAll 数据
        for (Map<String, Object> item : sciListAllName) {
            Integer status = (Integer) item.get("status");
            String msgType = (String) item.get("msgType");

            // 1. 根据 status 分类
            if (status == 3 || status == 4) { // 属于 audit
                // 2. 根据 msg_type 分类，检查 audit 中是否有该类型的列表
                audit.putIfAbsent(msgType, new ArrayList<>());
                // 将当前对象添加到对应类型的列表
                audit.get(msgType).add(item);
            } else if (status == 0|| status == 1 || status == 2) { // 属于 reject
                // 2. 根据 msg_type 分类，检查 reject 中是否有该类型的列表
                reject.putIfAbsent(msgType, new ArrayList<>());
                // 将当前对象添加到对应类型的列表
                reject.get(msgType).add(item);
            }
        }

        // 将分类结果放入最终的 result map 中
        result.put("audit", audit);
        result.put("reject", reject);
        System.out.println(result);
//        System.out.println(result);
        return result;
    }


    public Map<String, List<String>> groupByType(List<SciMessage> messages) {
        Map<String, List<String>> groupedSciIds = new HashMap<>();
        for (SciMessage message : messages) {
            String type = message.getType();
            String sciId = message.getSciId();
            // 如果该类型还没有对应的 List，就新建一个 List
            groupedSciIds.putIfAbsent(type, new ArrayList<>());
            // 添加 sciId 到对应的 List 中
            groupedSciIds.get(type).add(sciId);
        }
        return groupedSciIds;
    }

    public R<String> deleteByMsg(SciMessage sciMessage) {
        String msgId = sciMessage.getId();
        String tableName = TypeTableUtil.getTableName(sciMessage.getType()) ;
        if(Objects.equals(msgId, "") ||msgId==null){
            msgId = findIdBySciId(sciMessage.getSciId());
            sciMessage.setId(msgId);
        }
        removeById(msgId);
        return this.baseMapper.deleteByMsg(tableName,sciMessage) ? R.OK("删除成功") : R.NG("删除成功");
    }

    public boolean deleteBySciIds(List<String> ids) {
        return this.baseMapper.deleteBySciIds(ids);
    }
}
